import { defineStore } from 'pinia'
export const documentStore = defineStore('document', () => {
    const document = ref<Documents[]>([{
        title: '默认文档',
        id: 1,
        sections: []
    }])
    const nowDocumentId = ref<DocumentId>(1)
    const nowSectionId = ref<SectionId>('')
    const getNowDocument = computed(() => document.value.find(item => item.id === nowDocumentId.value))
    const getDocument = computed(() => document)
    const nowDocumentIndex = computed(() => document.value.findIndex(item => item.id === nowDocumentId.value))
    const nowSectionIndex = computed(() => getNowDocument.value?.sections.findIndex(item => item.id === nowSectionId.value))
    const getAllDocument = () => document.value.map(item => {
        return {
            ...item,
            sections: item.sections.map(item => {
                const { content, ...rest } = item
                return rest
            })
        }
    })
    const getOneDocument = (id: DocumentId) => document.value.find(item => item.id === id)
    const addSection = (title: string) => {
        const index = document.value.findIndex(item => item.id === nowDocumentId.value)
        if (index !== -1) {
            const sectionId = `id-${uuidV4()}`
            document.value[index].sections.push({
                title,
                id: sectionId,
                content: '',
                create: new Date(),
                update: new Date(),
                readonly: false
            })
            nowSectionId.value = sectionId
        }
    }
    const setNowSectionId = (id: SectionId) => {
        nowSectionId.value = id
    }
    const deleteSection = (dId: DocumentId, sId: SectionId) => {
        const nowSeIndex = unref(nowSectionIndex)
        const index = document.value.findIndex(item => item.id === (dId === -1 ? getNowDocument.value?.id : dId))
        if (index === -1) {
            return
        }
        const sectionIndex = document.value[index].sections.findIndex(item => item.id === sId)
        if (sectionIndex === -1) {
            return
        }
        document.value[index].sections.splice(sectionIndex, 1)
        if (nowSectionId.value !== sId) {
            return
        }
        if (nowSeIndex === 0) {
            setNowSectionId(getNowDocument.value!.sections[nowSeIndex]?.id)
        } else {
            setNowSectionId(getNowDocument.value!.sections[nowSeIndex! - 1]?.id)
        }
    }
    return {
        deleteSection,
        getOneDocument,
        getAllDocument,
        getDocument,
        getNowDocument,
        addSection,
        nowDocumentIndex,
        nowSectionIndex,
        document,
        nowSectionId,
        setNowSectionId
    }
})